package com.junjie.controller;

import com.alibaba.fastjson.JSONObject;
import com.junjie.utils.CommonResult;
import com.junjie.utils.JWTUtils;
import com.junjie.utils.createVerificationCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
@RequestMapping("/util")
@ResponseBody
@Slf4j
public class UtilController {

    static String CODE;

    /**
     * 生成随机验证码图片
     *
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/getCodeImg")
    public void getIdentifyImage(@RequestParam(required = false) String id, HttpServletResponse response) throws IOException {
        log.info("执行了===>UtilController中的getIdentifyImage方法");
        //设置不缓存图片
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "No-cache");
        response.setDateHeader("Expires", 0);
        //指定生成的响应图片
        response.setContentType("image/jpeg");
        createVerificationCode code = new createVerificationCode();
        BufferedImage image = code.getIdentifyImg();
        code.getG().dispose();
        //将图形验证码IO流传输至前端
        ImageIO.write(image, "JPEG", response.getOutputStream());
        CODE = code.getCode();
    }

    //获取当前生成的验证码用于与前端输入的做比较
    @RequestMapping("/getCode")
    public CommonResult<String> getCode() {
        return new CommonResult<>(200, CODE);
    }

    //前端获取 JWT 中隐藏的数据
    @RequestMapping(value = "/getJWTMessage",method = RequestMethod.POST)
    public CommonResult getJWTMessage(@RequestBody JSONObject json) {
        String res = JWTUtils.getTokenStringValue(json.getString("token"), json.getString("keyName"));
        try {
            Integer ires = Integer.parseInt(res);
            return new CommonResult(200, "Token 信息获取成功！", ires);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        return new CommonResult(200, "Token 信息获取成功！", res);
    }
}
